﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using CommModule.Security;

namespace CommModule.Messages
{
    public class SecChannelChallengeMessage: Convertible
    {
        private String _cipheredChallenge;

        public SecChannelChallengeMessage() { }

        public SecChannelChallengeMessage(int clientChallenge, int serverChallenge, byte[] sessionKey)
        {
            int challenge = clientChallenge + serverChallenge;

            _cipheredChallenge = SimmEncryption.Cipher(challenge.ToString(), sessionKey);
        }

        public int GetChallenge(byte[] sessionKey)
        {
            String clientChallenge = SimmEncryption.Decipher(_cipheredChallenge, sessionKey);
            return int.Parse(clientChallenge);
        }


        public void ConvertToCanonic(XmlWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("SecChannelChallengeMessage");

            if (_cipheredChallenge != null)
            {
                xmlWriter.WriteStartElement("CipheredChallenge");
                xmlWriter.WriteString(_cipheredChallenge);
                xmlWriter.WriteEndElement();
            }

            xmlWriter.WriteEndElement();
        }

        public void ConvertFromCanonic(XmlTextReader xmlTextReader)
        {
            xmlTextReader.ReadStartElement();

            if (xmlTextReader.Name == "CipheredChallenge")
            {
                _cipheredChallenge = xmlTextReader.ReadElementContentAsString();
            }

            xmlTextReader.ReadEndElement();
        }
    }
}
